package com.nciae.utils;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.*;

public class HttpUtils {


    private static final ObjectMapper mapper = new ObjectMapper();
    /**
     * 返回操作Http请求的类
     * @return
     */
    public static CloseableHttpClient getHttpClient() {
        CloseableHttpClient client = HttpClientBuilder.create().build();
        return client;
    }

    /**
     * 返回HTTP响应对象
     * @return
     */
    public static CloseableHttpResponse getHttpResponse() {
        CloseableHttpResponse response = null;
        return response;
    }

    /**
     * 返回HttpGet对象
     * @param URI：
     * @return
     */
    public static HttpGet getHttpGet(String URI) {
        HttpGet httpGet = new HttpGet(URI);
        httpGet.setHeader("Content-Type","application/json");
        return httpGet;
    }

    /**
     * 返回HttpPost对象
     * @param URI：
     * @return
     */
    public static HttpPost getHttpPost(String URI) {
        HttpPost httpPost = new HttpPost(URI);
        httpPost.setHeader("Content-Type","application/json");
        return httpPost;
    }

    /**
     * 返回HttpPut对象
     * @param URI：
     * @return
     */
    public static HttpPut getHttpPut(String URI) {
        HttpPut httpPut = new HttpPut(URI);
        httpPut.setHeader("Content-Type","application/json");
        return httpPut;
    }
    /**
     * 返回HttpDelete对象
     * @param URI：资源
     * @return
     */
    public static HttpDelete getHttpDelete(String URI) {
        HttpDelete httpDelete = new HttpDelete(URI);
        httpDelete.setHeader("Content-Type","application/json");
        return httpDelete;
    }

    /**
     * 执行请求：GET，POST，PUT，DELETE
     * @param httpUriRequest：各类请求的父类
     * @return
     * @throws IOException
     */
    public static String excute(HttpUriRequest httpUriRequest) throws IOException {
        // HTTP客户端
        CloseableHttpClient httpClient = getHttpClient();
        // 响应对象
        CloseableHttpResponse response = getHttpResponse();
        // 执行HTTP请求
        response = httpClient.execute(httpUriRequest);
        // 得到方法体的字节流
        InputStream content = response.getEntity().getContent();
        // 转化成字符流
        Reader reade = new InputStreamReader(content);
        // 加工成字符缓冲流
        BufferedReader reader = new BufferedReader(reade);
        // 使用SpringBuffer
        StringBuffer sb = new StringBuffer();
        // 代表字节流中一行字符串
        String line;
        // 方法体中字节转化成字符串存放到StringBuffer中
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        // 以字符串的形式返回方法体中的内容
        return sb.toString();
    }

}